<template>
  <div class="app-container documentation-container">
    <div class="graph_wrapper" id="graph_wrapper">
      <div :class="{ example: true, hide: !isVisible }" id="example">
        <div :class="{ graph_title: true, long: detail.projectName && detail.projectName.length > 6 }">
          {{ detail.projectName }}
          <span style="float: right" @click="hideMax">关闭</span>
        </div>
        <div v-loading="loading" id="exampleMap" class="exampleMap"> </div>
      </div>
      <el-carousel trigger="click" :autoplay="autoplay" id="carousel" :class="{ carousel: true, hide: isVisible }" :interval="15000" indicator-position="outside" >
        <el-carousel-item v-for="(item, index) in maps" :key="index" class="graph_container">
          <div :class="{ graph_title: true, long: item.projectName && item.projectName.length > 6 }"> {{ item.projectName }}</div>
          <!-- <div class="graph_box" :id="'graph' + m.projectId" style="min-width: 300px; min-height:300px;"> </div> -->
          <div class="total">设备总数: {{item.devCount}}</div>
            <!-- style="min-width: 300px; width: 100%; min-height:260px;"  -->
          <img
            @click="show(item)"
            :width="item.width"
            :height="item.height"
            :src="'http://api.map.baidu.com/staticimage/v2?ak='+ ak + '&width=' + item.width +'&height='+ item.height + '&copyright=1' + item.zoom +'&scale=1' + item.center + item.markers + item.markerStyles"/>
        </el-carousel-item>
      </el-carousel>

    </div>
  </div>
</template>

<script>
import Graph from './graph.vue'
// import echarts from 'echarts'
import { loadProjectList, myProjectDetail, movePoint } from '@/api/myProject'
import loadBMap from '@/utils/loadBMap'
export default {
  name: 'projectGraph',
  components: { Graph },
  data() {
    return {
      ak: 'k5LYzWjOinI5GOcHpBgdxieo5ZVPGtLj',
      loading: true,
      isVisible: false,
      autoplay: true,
      detail: { projectName: '北京'},
      mapExample: null,
      maps: [ ],
      projects: [],
      blueIcon: null,
      greenIcon: null,
      yellowIcon: null,
      redIcon: null,
      dredIcon: null,
      pColors:{
        0: this.greenIcon,
        1: this.blueIcon,
        2: this.yellowIcon, // 黄色
        3: this.redIcon,
        4: this.dredIcon
      }
    }
  },
  mounted() {
    // 百度地图版本
    this.initSize()
  },
  methods: {
    show(mapObj){
      this.autoplay = false
      // this.detail =  {
      //     points: mapObj.devices,
      //     ...mapObj
      //   }
      // this.showBigMap()
      let id = mapObj.projectId  //
      myProjectDetail(id).then(res => {
        this.detail = {
          points: res.data,
          ...mapObj
        }
        this.showBigMap()
      }).catch()
    },
    showBigMap(index, i){
      this.loading = true
      this.isVisible = true
      this.mapExample.clearOverlays()
      let pArray = []
      this.detail.points.map(p => {
        if(p.longitude && p.latitude){

          let lng = parseFloat(p.longitude), lat = parseFloat(p.latitude)
          let _point = new BMapGL.Point(lng, lat)
          pArray.push(_point)
          let marker = new BMapGL.Marker(_point, {
            icon: this.pColors[p.dataStatus],
            enableDragging: this.$store.state.user.accountType == 0
          });
          this.mapExample.addOverlay(marker); // 将标注添加到地图

          // console.log(marker,p.dataStatus, icon,this.blueIcon)
          let dragEndPoint = _point
            marker.addEventListener("dragend", () => {
                let curPoint = marker.getPosition();
                dragEndPoint = curPoint
                console.log('拖拽位置', curPoint)
                movePoint({
                  deviceId: p.id,
                  longitude: curPoint.lng,
                  latitude: curPoint.lat
                }).then(res => {
                  if(res.statusCode == '200') {
                    this.$message.success('重新定位成功！')
                  }
                }).catch()
            }, { passive: false});

            marker.addEventListener("click", () => {
                let curPoint = marker.getPosition();
                // console.log('点击事件位置', curPoint)
                 let opts = {
                    width: 280,
                    height: 160,
                    title:  `设备名称：${p.deviceName} `
                };
                let info = `
                IMEI： ${p.imei} <br>
                自定义编码： ${p.deviceCode} <br>
                电子标签： ${p.rfid} <br>
                经度： ${curPoint.lng} <br>
                纬度： ${curPoint.lat} <br>
                安装时间：${p.insTime} <br>`
                let infoWindow = new BMapGL.InfoWindow( info, opts);
                this.mapExample.openInfoWindow(infoWindow, dragEndPoint); // 开启信息窗口
            },  { passive: false});

        }


      })
      setTimeout(() => {
         this.loading = false
      }, 500)

      // console.log('省图',this.detail.provinceName)
      let area = this.detail.countyName || this.detail.cityName || this.detail.provinceName
      if(pArray.length > 0){
         this.mapExample.setViewport(pArray) // 调整视野
      } else {
        this.drawBoundary(area, this.mapExample)
      }

    },
    hideMax(){
      this.isVisible = false
      this.autoplay = true
    },
    drawBoundary(provinceName, map){
       // 设置区域覆盖物
        var bd = new BMapGL.Boundary()
        bd.get(provinceName, (rs) => { // 获取行政区域
          // map.clearOverlays() // 清除地图覆盖物
          var count = rs.boundaries.length // 行政区域的点有多少个
          // 包含所有区域的点数组
          let pointArray = []
          // 为目标省会绘图（添加覆盖物）
          for (var i = 0; i < count; i++) {
            let ply = new BMapGL.Polygon(rs.boundaries[i],
              { strokeWeight: 5,
               strokeOpacity:1, //设置多边形边线透明度0-1
                StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashedstrokeColor:"#ff0000", //设置多边形边线颜色
              // strokeColor: "#FF0000",
                strokeColor: '#003088',
                fillOpacity: 0.01,  //设置多边形填充颜色透明度0-1
                fillColor: ' #FFFFFF' } // //设置多边形填充颜色
            )
            let path = ply.getPath()
            pointArray = pointArray.concat(path)

            map.addOverlay(ply) // 添加覆盖物
          }

          map.setViewport(pointArray) // 调整视野
        })
    },
    initSize(){

      let width = document.body.clientWidth - 200 * 2
      let height = document.body.clientHeight - 65 - 30 * 2
      document.getElementById('graph_wrapper').style.width = width + 'px'
      document.getElementById('graph_wrapper').style.height = height + 'px'


      loadBMap("k5LYzWjOinI5GOcHpBgdxieo5ZVPGtLj").then(res => {
        this.blueIcon = new BMapGL.Icon("/imgs/blueP.png", new BMapGL.Size(14, 27));
        this.greenIcon = new BMapGL.Icon("/imgs/greenP.png", new BMapGL.Size(14, 27));
        this.yellowIcon = new BMapGL.Icon("/imgs/yellowP.png", new BMapGL.Size(14, 27));
        this.redIcon = new BMapGL.Icon("/imgs/redP.png", new BMapGL.Size(14, 27));
        this.dredIcon = new BMapGL.Icon("/imgs/dredP.png", new BMapGL.Size(14, 27));

        this.pColors ={
          0: this.greenIcon,
          1: this.blueIcon,
          2: this.yellowIcon, // 黄色
          3: this.redIcon,
          4: this.dredIcon
        }
        this.mapExample = new BMapGL.Map('exampleMap') // 创建地图实例
        this.mapExample.centerAndZoom('郑州市', 7) // 初始化地图，设置中心点坐标和地图级别
        this.mapExample.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
        this.mapExample.addControl(new BMapGL.ScaleControl()) // 添加比例尺控件
        this.mapExample.addControl(new BMapGL.ZoomControl())
        window.addEventListener("touchmove", () => {}, { passive: false})
      }).catch(err => {
        console.log("地图加载失败")
      })
    }
  },
  created(){
    this.projects = []
    this.$store.state.user.projects = []
    loadProjectList({
      userId: this.$store.state.user.id,
      status: this.$store.state.user.userInfo.status,
      accountType: this.$store.state.user.userInfo.accountType,
      city: this.$store.state.user.userInfo.city,
      county: this.$store.state.user.userInfo.county,
      province: this.$store.state.user.userInfo.province
    }).then(res => {
        this.$store.state.user.projects = [ ...res.data]
        this.projects = []
        let width = (Number.parseFloat(document.getElementById('graph_wrapper').style.width) -100)
        let height =  (Number.parseFloat(document.getElementById('graph_wrapper').style.height) - 220)
        // let url =  "http://47.107.154.195/"
        let url = window.location.origin
        let Colors = {
          0: '/imgs/greenP.png',
          1: '/imgs/blueP.png',
          2: '/imgs/yellowP.png', // 黄色
          3: '/imgs/redP.png',
          4: '/imgs/dredP.png'
        }
        let _markerStyles = []
        res.data.map(v => {
          let markers = []
          v.devices.map(d => {
            if(d.longitude && d.latitude) {
             markers.push( d.longitude + ',' + d.latitude)
             _markerStyles.push(
                 '-1,' + url + Colors[d.dataStatus] + ',-1,14,27'
                //  '-1,' + url + Colors[0] + ',-1,14,27'
             )
            }
          })
          this.projects.push({
            width: width > 1024 ? 1024 : width,
            height: height > 1024 ? 1024 : height,
            markersPoints: markers,
            path: '&paths=' +   markers.join('|'),
            // path: '&paths=' + (v.countryName? v.countryName: ''),
            zoom: '&zoom=' + (markers.length > 0 ? 18 : 15),
            // zoom: '&zoom=' + (markers.length > 0 ? 16 : 15),
            center: '&center=' + (markers.length > 0 ? markers[0]: v.provinceName + (v.cityName? v.cityName: '' )+ (v.countryName? v.countryName: '')),
            markers: "&markers=" + markers.join('|'),
            markerStyles: "&markerStyles=" + _markerStyles.join('|'),
            // markerStyles: "&markerStyles=-1,http://47.107.154.195/imgs/blueP.png,-1,14,27|-1,http://47.107.154.195/imgs/redP.png,-1,14,27|-1,http://47.107.154.195/imgs/greenP.png,-1,14,27",
            ...v
          })
        })
        this.$store.state.user.projects = [...this.projects]
        // let page = Math.ceil( this.projects.length / 4 )
        // let temp = []
        // let width = (Number.parseFloat(document.getElementById('graph_wrapper').style.width) -140)/2
        // let height =  (Number.parseFloat(document.getElementById('graph_wrapper').style.height) -320) /2
        // for( let i = 0; i < page ; i++ ){
        //   let graphsArr = this.projects.splice( 0 , 4)
        //   if(graphsArr.length > 0) {
        //     temp.push({
        //       graphs:  graphsArr,
        //       width: width > 512 ? 512 : width,
        //       height: height > 512 ? 512 : height,
        //      })
        //   }
        // }
        this.maps =  [...this.projects]

    }).catch()

  },
  destroyed(){
  /**
  * 销毁百度地图
    */
    try {
      // 注销地图（换成你初始化时定义的地图变量）
      this.mapExample = null;

      // 获取interval的最高ID然后遍历清除
      const HIGHEST_INTERVAL_ID = setInterval(';');
      for ( let i = 0 ; i < HIGHEST_INTERVAL_ID ; i++ ) {
        clearInterval(i);
      }

      // 获取百度地图创建的DOM并销毁
      const BAIDU_MAPS = document.querySelectorAll('.tangram-suggestion-main');
      BAIDU_MAPS.forEach( item => {
        document.body.removeChild(item);
      });

    } catch (e) {
      // console.log(e);
    }
  }
}
</script>

<style lang="scss" >
.hide {
  visibility: hidden;
}
.graph_wrapper {
  margin: 30px auto;
  position: relative;
}
.example {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: calc( 100% - 60px);
  background: #0B1120;
  padding: 30px 50px;
  background: url('../../assets/imgs/map_bg.png') no-repeat;
  background-size: 100% 100%;
  .exampleMap {
    width: 100%;
    height: calc( 100% - 70px);
    // height: 100%;
    touch-action:none
  }
  .graph_title {
    color: #fff;
    font-size: 14px;
    background: url('../../assets/imgs/map_title_small.png') no-repeat;
    padding: 5px 20px;
    margin-bottom: 20px;
    &.long {
      background: url('../../assets/imgs/map_title_long.png') no-repeat;
    }
    span {
      cursor: pointer;
    }
  }
}

.carousel {
  width: 100%;
  height: 100%;
  // height: 800px;
  // margin: 30px auto;
  .el-carousel__item.is-animating {
    transition: transform 5s ease-in-out, -webkit-transform 5s ease-in-out;
  }
  .el-carousel__container {
    width: 100%;
    height: calc( 100% - 60px);
    .graph_container {
     width: 100%;
     height: 100%;
      background: url('../../assets/imgs/map_bg.png') no-repeat;
      background-size: 100% 100%;
      padding: 30px 50px 10px;
      text-align: center;

    }
    img {
        border-radius: 5px;
      }
  }
  .graph_title {
    color: #fff;
    font-size: 14px;
    background: url('../../assets/imgs/map_title_small.png') no-repeat;
    // background-size: 100% 100%;
    padding: 5px 20px;
    text-align: left;
    &.long {
      background: url('../../assets/imgs/map_title_long.png') no-repeat;
    }

  }

  .total {
    color: #fff;
    margin: 10px 0;
    text-align: left;
  }
  .graph_box {
    // height: calc(100% - 60px);
    height: calc(100% - 30px);
    touch-action:none
    // width: 300px;
    // height: 300px;
  }


}



.documentation-container {
  // margin: 0 20px;
  // padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  position: relative;
  // background: #fff;

  .document-btn {
    flex-shrink: 0;
    display: block;
    cursor: pointer;
    background: black;
    color: white;
    height: 60px;
    padding: 0 16px;
    margin: 16px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
}
</style>
